<?php
/**
 * 自动打包程序
 *
 * PHP version 5
 *
 * @package   AutoPack
 * @author Giles <giles.wang@icloud.com>
 * @version V1.1
 */

class AutoPack
{
    //打包类型
    protected $type = '2'; //1 为自动单个打包 2 自动批量打包(批量打包要保证包的名字和配置文件名字一致否则打包会失败)
    protected $packType = '2'; //1 i苹果包  2 游戏包
    protected $packName = ''; //包的名字 批量打包的时候不必提供
    protected $confName = ''; //配置文件名字 批量打包的时候不必提供
    protected $dir = '';
    protected $channelId  = '2001000101';
    protected $certificate = 'iPhone Developer: Zhibin Wang (7R28ZQL59M)';
    protected $jpush = array(
            //'Kerulen.ipa'  =>  '18681f28529617eae51d548e',
            //'Fangsheng.ipa'  =>  'de58537ad1c3780146f6ddb3',
            //'baiyun_dis.ipa'  =>  '7b69cc65969996cccad09ad2',
            'gaoke_dis.ipa'  =>  'f32486e7fc7a3644c596c2d8',
    );

    function __construct()
    {
        $this->dir = dirname(__FILE__). '/';
    }

    /**
     * 解析配置文件
     * @author Giles <giles.wang@iclode>
     * @return array
     *
     */
    function analysis()
    {
        if(empty($this->confName)){
            die("配置文件载入失败");
        }

        exec("security cms -D -i ". $this->dir. 'packageold/'. $this->confName ." > temp.xml");

        $return = array();
        $xmlData = simplexml_load_file('temp.xml');
        $string = (array) $xmlData->dict->string;
        if($this->channelId == '3001000101') {
            $return['certificate'] = $this->certificate;
        }else {
            $return['certificate'] = 'iPhone Distribution: '.$string[2];
        }

        $bundleTemp = (array) $xmlData->dict->dict->string;
        $bundlitem = $bundleTemp[0];
        $temp = explode('.', $bundlitem);
        $return['itermid'] = $temp[0];
        unset($temp[0]);
        $return['bundleId'] = implode('.', $temp);
        $return['certificatemd5'] = md5($return['certificate']);

        if($this->packType == 1) {
            $return['jpushappkey']    = $this->jpush[$this->packName];
        }
        return $return;
    }


    /**
     * 执行打包程序
     *
     * @author Giles <giles.wang@icloud.com>
     * @return Void
     *
     */
    function run()
    {

        $files = glob('packageold/*.ipa');
        foreach($files as $file) {
            $fileTemp = explode('/', $file);
            $this->packName = $fileTemp[1];
            $confTemp = explode('.', $this->packName);
            $this->confName = $confTemp[0] .'.mobileprovision';
            if(!is_file('packageold/'.$this->confName)) {
                exit("包:". $this->packName .'的配置文件不存在！');
            }

            $config = $this->analysis();
            $this->pack($config);
        }
    }

    function pack($config)
    {
        echo $this->packName." --开始打包\n";
        exec("unzip -q packageold/".$this->packName);
        exec("chmod -R 777 ./Payload");
        exec("chmod 777 ./temp.entitlements");

        $dirs = $this->getDir('Payload');

        if($config['bundleId'] == '*') {
            	$actionsss = '/usr/libexec/plistbuddy -c "Print CFBundleIdentifier" '.$dirs .'Info.plist';
		exec($actionsss, $actions, $cobak);
		$config['bundleId'] = $actions[0];
        }
        exec("cp ". $this->dir. 'packageold/'. $this->confName." ".$dirs ."embedded.mobileprovision");
        //下面这行注释了就是不改bundle id
        //exec("/usr/libexec/plistbuddy -c 'Set :CFBundleIdentifier \"". $config['bundleId'] ."\"'  ".$dirs ."Info.plist");
        $isAdd = "/usr/libexec/plistbuddy -c 'Add :CerBundleID String \"". $config['certificatemd5'] ."|".$this->channelId."\"' ". $dirs ."Info.plist";
        exec($isAdd, $actions, $cobak);
        if($cobak != 0) {
           	echo "使用Add失败，尝试用Set 忽略Add报错信息\n";	
            $set = "/usr/libexec/plistbuddy -c 'Set :CerBundleID \"". $config['certificatemd5'] ."|".$this->channelId."\"' ". $dirs ."Info.plist";
		 exec($set);
        }
        //exec("/usr/libexec/plistbuddy -c 'Set :CerBundleID \"". $config['certificatemd5'] ."|".$this->channelId."\"' ". $dirs ."Info.plist");
        if ($this->packType == 1) {
            exec("/usr/libexec/plistbuddy -c 'Set :APP_KEY \"". $config['jpushappkey'] ."\"' ". $dirs ."PushConfig.plist");
        }
        exec("/usr/libexec/plistbuddy -c 'Set :application-identifier \"". $config['itermid'] .".". $config['bundleId'] ."\"' ./temp.entitlements");
        exec("/usr/libexec/plistbuddy -c 'Set :com.apple.developer.team-identifier \"". $config['itermid'] ."\"' ./temp.entitlements");
        exec("/usr/libexec/plistbuddy -c 'Set :keychain-access-groups:0 \"". $config['itermid'] .".*\"' ./temp.entitlements");
        $cuk = $config['certificate'];

        $action = "/usr/bin/codesign --preserve-metadata=identifier,entitlements -f -s \"".  $cuk ."\" --identifier \"". $config['bundleId'] ."\" --entitlements ./temp.entitlements ". $dirs;
        exec($action, $actions, $cobak);
        if($cobak != 0){
            exec('rm -rf Payload');
            echo $this->packName ."签名失败\n";
		return;
        };
        exec("zip -r -q temp.ipa Payload/");
        $newFile = rtrim($this->getPackName($this->packName));
        rename('temp.ipa', './package/'. $newFile .'-'.date('md').'-'.$this->channelId.'.ipa');
        exec('rm -rf Payload');
        exec('rm -rf __MACOSX');
        echo $this->packName.' --打包完成！';
    }

    /**
     *   获取包的名字
     */
    function getPackName($packs){
        $temp  = explode('.', $packs);
        return $temp[0];
    }

    /**
     * 获取解压后的包路径
     */
    function getDir($dir) {
        $dirArray[]=NULL;
        //echo $dir;
        if (false != ($handle = opendir ($dir))) {
            $i=0;
            while ( false !== ($file = readdir($handle))) {
                //去掉"“.”、“..”以及带“.xxx”后缀的文件
                //var_dump($file);
                if (strpos($file, '.app')) {
                    $dirArray[$i]=$file;
                    $i++;
                }
            }
            //关闭句柄
            closedir ($handle);
        }
        $lastDir = $dir . '/'. $dirArray[0].'/';
        if(strpos($lastDir, ' ')) {
            $lastDir = str_replace(' ', '\ ', $lastDir);
        }
        return $lastDir;
    }

}


$pack = new AutoPack();
exec('security unlock-keychain "-p" "jufeng123" /Users/pack/Library/Keychains/login.keychain');
//exec('security unlock-keychain "-p" "jufeng123" /Users/pack/Desktop/归档/iiapplegame.keychain');
//exec('security unlock-keychain "-p" "jufeng123" /Library/Keychains/System.keychain');
$pack->run();

